package com.yeswater.multithread.chapter6;

/**
 * author : yeswater
 * date : 2023/10/24
 */

public class Run_6_1_5 {
    public static void main(String[] args) {
        MyThread t1 = new MyThread();
        MyThread t2 = new MyThread();
        MyThread t3 = new MyThread();

        t1.start();
        t2.start();
        t3.start();
    }

    private static class MyThread extends Thread {
        @Override
        public void run() {
            System.out.println(MyObject.getInstance().hashCode());
        }
    }

    private static class MyObject {
        private static MyObject myObject;

        private MyObject() {

        }

        /**
         * 多线程环境会出现取出多个实例的情况
         */
        public static MyObject getInstance() {
            try {
                if (myObject == null) {
                    // 模拟在创建对象之间做一些准备工作
                    Thread.sleep(3000);
                    // 只锁部分代码 多线程状态下 可能多个线程都会通过判断 等待锁 然后每个线程各自创建一个对象
                    synchronized (MyObject.class) {
                        if (myObject == null) {
                            myObject = new MyObject();
                        }
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return myObject;
        }
    }
}
